{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "15\n",
      "15.0\n"
     ]
    }
   ],
   "source": [
    "#从数组中选取任意个元素 让其和最大  要求任意两个元素不能相邻。\n",
    "import numpy as np\n",
    "\n",
    "arr = [ 1, 2, 4, 1, 7, 8, 3]\n",
    "\n",
    "def rec_opt(arr, i):\n",
    "    if i == 0:\n",
    "        return arr[0]\n",
    "    elif i == 1:\n",
    "        return max(arr[0], arr[1])\n",
    "    else :\n",
    "        A = rec_opt(arr, i - 2) + arr[i]\n",
    "        B = rec_opt(arr, i - 1)\n",
    "        return max(A, B)\n",
    "    \n",
    "print(rec_opt(arr, 6))\n",
    "\n",
    "def dp_opt(arr):\n",
    "    opt = np.zeros(len(arr))\n",
    "    opt[0] = arr[0]\n",
    "    opt[1] = max(arr[0], arr[1])\n",
    "    \n",
    "    for i in range(2, len(arr)):\n",
    "        A = opt[i - 2] + arr[i]\n",
    "        B = opt[i - 1]\n",
    "        opt[i] = max(A, B)\n",
    "        \n",
    "    return  opt[len(arr)-1]\n",
    "\n",
    "print(dp_opt(arr))\n",
    "    "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
